package com.wenhao.leetcode.medium;

import com.wenhao.leetcode.structure.TreeNode;

import java.util.HashMap;
import java.util.Map;
/**
 * 题目：https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
 * 从前序与中序遍历序列构造二叉树
 * @author Wenhao Tong
 * @date
 */
public class LeetCode105 {
    public static void main(String[] args) {

    }

    Map<Integer, Integer> inorderIndex = new HashMap<>();

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        for (int i = 0; i < preorder.length; i++) {
            inorderIndex.put(inorder[i], i);
        }
        return getSubTree(preorder, 0, 0, preorder.length);
    }

    private TreeNode getSubTree(int[] preorder, int preLo, int inLo, int size) {
        if (size == 0) {
            return null;
        }
        TreeNode treeNode = new TreeNode(preorder[preLo]);
        int index = inorderIndex.get(preorder[preLo]);
        int size1 = index - inLo;
        TreeNode leftChild = getSubTree(preorder, preLo + 1, inLo, size1);
        TreeNode rightChild = getSubTree(preorder, preLo + 1 + size1, inLo + size1 + 1, size - size1 - 1);
        treeNode.left = leftChild;
        treeNode.right = rightChild;
        return treeNode;
    }
}
